<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "cart".
 *
 * @property int $id
 * @property string $seller 卖家名称
 * @property int $sellerid 卖家ID
 * @property int $goods_id 商品
 * @property string $goodsname 商品名称
 * @property string $price 价格
 * @property string $install_price 每月安装制作费用价格
 * @property string $total_price 总价
 * @property int $nums 数量
 * @property int $have_package 是否含套餐
 * @property string $package_info 套餐信息包含套餐id,名称,单价,数量;
 * @property int $status 状态
 * @property int $addtime 添加时间
 */
class Cart extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cart';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['seller', 'sellerid', 'goods_id', 'goodsname', 'total_price', 'status', 'addtime'], 'required'],
            [['sellerid', 'goods_id', 'nums', 'addtime'], 'integer'],
            [['price', 'total_price'], 'number'],
            [['seller', 'goodsname'], 'string', 'max' => 150],
            [['package_info'], 'string', 'max' => 8000],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'seller' => '卖家名称',
            'sellerid' => '卖家ID',
            'goods_id' => '商品',
            'goodsname' => '商品名称',
            'price' => '价格',
            'total_price' => '总价',
            'nums' => '数量',
            'have_package' => '是否含套餐',
            'package_info' => '套餐信息包含套餐id,名称,单价,数量;',
            'status' => '状态',
            'addtime' => '添加时间',
        ];
    }
    
    
    public static function addNoPackageGoodsToCart($userid,$goods,$nums){
        $model = new Cart();
        $model->seller = $goods->seller;
        $model->sellerid = $goods->seller_id;
        $model->userid = $userid;
        $model->goods_id = $goods->id;
        $model->goods_no = $goods->goods_no;
        $model->goodsname = $goods->name;
        $model->price = $goods->price;
        $model->install_price = $goods->install_price;
        $model->nums = $nums;
        $model->total_price = $nums*($goods->price+$goods->install_price);
        $model->have_package = $goods->have_package;
        $model->status = 0;
        $model->addtime = time();
        
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $exits = Cart::findOne(['userid'=>$userid,'goods_id'=>$goods->id]);
            if(!empty($exits) && !Cart::deleteAll(['userid'=>$userid,'goods_id'=>$goods->id])){
                throw new \Exception('删除原属性信息失败！');
            }
            
            if (!$model->save(false)) {
                \Yii::getLogger()->log($model->errors, \yii\log\Logger::LEVEL_ERROR);
                throw new \Exception('商品添加失败！');
            }
            
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            
            $output['success'] = 0;
            $output['msg'] = $e->getMessage();
            Tools::outputjson($output);
        }
        
        $output['success'] = 1;
        $output['msg'] = "添加成功！";
        Tools::outputjson($output);
    }
    
    public static function addPackageGoodsToCart($userid,$goods,$price,$install_price,$price_total,$goods_package_info){
        $model = new Cart();
        $model->userid = $userid;
        $model->seller = $goods->seller;
        $model->sellerid = $goods->seller_id;
        $model->goods_id = $goods->id;
        $model->goods_no = $goods->goods_no;
        
        $model->goodsname = $goods->name;
        $model->price = $price;
        $model->install_price = $install_price;
        $model->total_price = $price_total;
        $model->have_package = $goods->have_package;
        $model->package_info = $goods_package_info;
        $model->status = 0;
        $model->addtime = time();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $exits = Cart::findOne(['userid'=>$userid,'goods_id'=>$goods->id]);
                        
            if(!empty($exits) && !Cart::deleteAll(['userid'=>$userid,'goods_id'=>$goods->id])){
                throw new \Exception('删除原属性信息失败！');
            }
            
            if (!$model->save(false)) {
                \Yii::getLogger()->log($model->errors, \yii\log\Logger::LEVEL_ERROR);
                throw new \Exception('购物车添加失败！');
            }
            
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            
            $output['success'] = 0;
            $output['msg'] = $e->getMessage();
            Tools::outputjson($output);
        }
        
        $output['success'] = 1;
        $output['msg'] = "添加成功！";
        Tools::outputjson($output);
    }
    
    public static function getUserCartList($userid,$condition,$page_no){
        //获取卖家分页
        $perpage = 10;
        $sql_condition_arr = [];
        array_push($sql_condition_arr,'status=0');
        array_push($sql_condition_arr,'userid='.$userid);
        $sql_condition_string = implode(' and ', $sql_condition_arr);
        
        $data['total'] = self::getSellerCountByCondition($sql_condition_string);
        $begin = $perpage*($page_no-1);
        $cart_seller_data = self::getSellerByPage($sql_condition_string,$begin, $perpage);
        
        foreach($cart_seller_data as $seller_key=>$seller_val){
            $cartdata = self::getCartsBySeller($seller_val['sellerid']);
            foreach($cartdata as $key=>$value){
//                print_r($cartdata);
                $goods = Goods::findOne($value['goods_id']);
                if($value['have_package']==0){//不含套餐的购物车

                    switch($goods->first_cate){
                        case 1://广告位商品
                            if($goods->order_endtime < time() || $goods->last_buyerid == Yii::$app->user->identity->id){
                                //符合购买条件，商品未失效
                                $cartdata[$key]['disabled'] = 0;
                            }else{
                                $cartdata[$key]['disabled'] = 1;//商品已失效
                            }

                            break;
                        case 7://广告设备商品
                            if($goods->nums >= $value['nums']){
                                $cartdata[$key]['disabled'] = 0;
                            }else{
                                $cartdata[$key]['disabled'] = 1;//商品已失效
                            }
                            break;
                        default :
                            //do nothing
                    }
                }
                if($value['have_package']==1){//含套餐的购物车
                    //检测套餐是否失效
                    $packages = explode(';', $value['package_info']);
                    foreach($packages as $package){
                        if(!empty($package)){
                            $package_one = explode(',', $package);
                            $package_id = $package_one[0];
                            $package_buy_num = $package_one[1];
                            $package_model = GoodsPackage::findOne($package_id);
                        }
                        switch($goods->first_cate){
                            case 1://广告位商品，检测是否能够购买
                                if($package_model->buy_able_time < time() || $package_model->last_buyerid == Yii::$app->user->identity->id){
                                    //符合条件,商品未失效
                                    $cartdata[$key]['disabled'] = 0;
                                }else{
                                    $cartdata[$key]['disabled'] = 1;//商品已失效
                                }
                                break;
                            case 7://设备商品，检测套餐 库存是否符合
                                foreach($packages as $package){
                                    if($package_model->nums >= $package_buy_num || $package_model->last_buyerid == Yii::$app->user->identity->id){
                                        //符合条件,,商品未失效
                                        $cartdata[$key]['disabled'] = 0;
                                    }else{
                                        $cartdata[$key]['disabled'] = 1;//商品已失效
                                    }
                                }
                                break;
                            default:
                            //do nothing
                        }
                    }
                }
                $cartdata[$key]['img'] = GoodsImg::getDefaultGoodsimgByGoodsno($value['goods_no']);
                $cartdata[$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
            }
            $cart_seller_data[$seller_key]['goods'] = $cartdata;
        }
        
        $data['cartdata'] = $cart_seller_data;
        $data['pagenums'] = ceil($data['total']/$perpage);
        $data['page_no'] = $page_no;
        $data['perpage'] = $perpage;
        return $data;
    }
    
    
    public static function getSellerCountByCondition($sql_condition_string){
        $sql = "select COUNT(DISTINCT sellerid) total from cart where $sql_condition_string";
        $command = \Yii::$app->db->createCommand($sql);
    	$model = $command->queryOne();
        return $model['total'];
    }
    
    public static function getSellerByPage($sql_condition_string,$begin, $perpage){
        $sql = "select DISTINCT sellerid,seller from cart where $sql_condition_string order by addtime desc limit $begin,$perpage";
        $command = \Yii::$app->db->createCommand($sql);
    	return $model = $command->queryAll();
    }


    public static function getCountByCondition($sql_condition_string){
        $sql = "select count(id) total from cart where $sql_condition_string";
        $command = \Yii::$app->db->createCommand($sql);
    	$model = $command->queryOne();
        return $model['total'];
    }
    
    public static function getCartsBySeller($seller_id){
        $sql = "select * from cart where sellerid=$seller_id order by addtime desc";
        $command = \Yii::$app->db->createCommand($sql);
    	return $model = $command->queryAll();
    }
}
